﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using JSC.Portal.Module;
using JSC.Portal.Entities;
using JSC.Portal.Services;
using JSC.Core;
using JSC.Portal.Web.Helper;

namespace JSC.Portal.Web.App.Modules.LanguageSwitcher
{
    public class LanguageSwitcherModule : ModuleBase
    {
        private IPortalPageService _svc;

        public LanguageSwitcherModule(Section section) : base(section) 
        {
            _svc = FacadeFactory.CreateFacade<IPortalPageService>();
            DisplayMode = DisplayMode.Text;
            RedirectToUserLanguage = false;
        }
        
        protected override void ReadSectionSettings() 
        {
            base.ReadSectionSettings();
            SectionModulePropertyValue smpv = Section.Settings.SingleOrDefault(s => s.ModuleProperty.Name == "DISPLAY_MODE");
            if (smpv != null)
            {
                DisplayMode = (DisplayMode)Enum.Parse(typeof(DisplayMode), smpv.Value);
            }
            smpv = Section.Settings.SingleOrDefault(s => s.ModuleProperty.Name == "REDIRECT_TO_USER_LANGUAGE");
            if (smpv != null)
            {
                RedirectToUserLanguage = Convert.ToBoolean(smpv.Value);
            }
        }

        public override void Load()
        {
            base.Load();
            IPortalSiteService svc = FacadeFactory.CreateFacade<IPortalSiteService>();
            PortalSite site = svc.GetPortalSiteByUrl(UrlHelperExtension.GetHostUrl());
            RootPages = GetCultureRootPagesBySite(site);
        }

        private Dictionary<Language, PortalPage> GetCultureRootPagesBySite(PortalSite portalSite)
        {
            Dictionary<Language, PortalPage> result = new Dictionary<Language, PortalPage>();
            IList<Language> languages = Language.GetLanguages();
            foreach (PortalPage portalpage in _svc.GetLanguageRootPagesBySite(portalSite))
	        {
                Language l = languages.Single(x => x.Culture == portalpage.Language);
                result.Add(l, portalpage);
	        }
            return result;
        }

        public PortalPage GetRootPageByLanguageAndSite(string language, PortalSite portalSite)
        {
            return portalSite.PortalPages.SingleOrDefault(p => p.Parent == null && p.Language == language);
        }

        public DisplayMode DisplayMode
        {
            get;
            private set;
        }

        public bool RedirectToUserLanguage
        {
            get;
            private set;
        }

        public Dictionary<Language, PortalPage> RootPages
        {
            get;
            private set;
        }
    }

    public enum DisplayMode
    {
        Text,
        Flag,
        DropDown
    }
}
